import streamlit as st
import pandas as pd
from collections import defaultdict
import hashlib
import time

# 页面设置
st.set_page_config(
    page_title="心动互选 - 联谊活动",
    page_icon="??",
    layout="centered"
)

# 自定义CSS
st.markdown("""
<style>
    .main-header {
        font-size: 2.5rem;
        color: #FF6B6B;
        text-align: center;
        margin-bottom: 2rem;
    }
    .match-result {
        background: linear-gradient(135deg, #FFE8E8 0%, #FFD6D6 100%);
        border-radius: 15px;
        padding: 25px;
        margin: 15px 0;
        border-left: 5px solid #FF6B6B;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .vote-section {
        background: linear-gradient(135deg, #E7F3FF 0%, #D4E7FF 100%);
        border-radius: 10px;
        padding: 20px;
        margin: 15px 0;
    }
    .stButton button {
        background-color: #FF6B6B;
        color: white;
        border-radius: 8px;
        border: none;
        padding: 10px 20px;
        font-weight: bold;
        width: 100%;
    }
</style>
""", unsafe_allow_html=True)

# 初始化session state
if 'participants' not in st.session_state:
    st.session_state.participants = []
if 'votes' not in st.session_state:
    st.session_state.votes = {}
if 'current_user' not in st.session_state:
    st.session_state.current_user = None
if 'admin_password' not in st.session_state:
    st.session_state.admin_password = "admin2024"

# 标题
st.markdown('<div class="main-header">?? 心动互选 - 联谊活动</div>', unsafe_allow_html=True)

# 计算互投好感度
def calculate_mutual_affinity():
    if not st.session_state.votes:
        return {}
    
    mutual_affinity = defaultdict(dict)
    
    for user1, votes1 in st.session_state.votes.items():
        for user2, votes2 in st.session_state.votes.items():
            if user1 != user2 and user2 in votes1 and user1 in votes2:
                affinity_score = votes1[user2] + votes2[user1]
                mutual_affinity[user1][user2] = affinity_score
    
    return mutual_affinity

# 显示个人结果
def show_personal_results():
    mutual_affinity = calculate_mutual_affinity()
    
    if st.session_state.current_user in mutual_affinity:
        user_matches = mutual_affinity[st.session_state.current_user]
        
        if user_matches:
            max_score = max(user_matches.values())
            best_matches = [user for user, score in user_matches.items() if score == max_score]
            
            st.markdown("### ?? 您的最佳匹配结果")
            
            if len(best_matches) == 1:
                st.markdown(f"""
                <div class="match-result">
                    <h3 style="color: #FF6B6B; text-align: center;">? 最佳匹配 ?</h3>
                    <p style="text-align: center; font-size: 1.2rem;">您与 <strong style="color: #FF6B6B;">{best_matches[0]}</strong> 的互选好感度最高！</p >
                    <p style="text-align: center; font-size: 1.5rem;">好感度总分: <strong style="color: #FF6B6B;">{max_score}</strong> 分</p >
                </div>
                """, unsafe_allow_html=True)
            else:
                matches_str = "、".join(best_matches)
                st.markdown(f"""
                <div class="match-result">
                    <h3 style="color: #FF6B6B; text-align: center;">? 最佳匹配 ?</h3>
                    <p style="text-align: center; font-size: 1.2rem;">您与 <strong style="color: #FF6B6B;">{matches_str}</strong> 的互选好感度并列最高！</p >
                    <p style="text-align: center; font-size: 1.5rem;">好感度总分: <strong style="color: #FF6B6B;">{max_score}</strong> 分</p >
                </div>
                """, unsafe_allow_html=True)
        else:
            st.info("暂未发现与您互相选择的匹配对象")
    else:
        st.info("暂未发现与您互相选择的匹配对象")

# 侧边栏 - 管理员功能
with st.sidebar:
    st.header("?? 管理员设置")
    
    admin_password_input = st.text_input("管理员密码", type="password")
    if st.button("进入管理员模式"):
        if admin_password_input == st.session_state.admin_password:
            st.session_state.admin_mode = True
            st.success("已进入管理员模式")
            st.rerun()
        else:
            st.error("密码错误")
    
    if st.session_state.get('admin_mode'):
        st.subheader("管理员功能")
        if st.button("退出管理员模式"):
            st.session_state.admin_mode = False
            st.session_state.current_user = None
            st.rerun()
        
        if st.button("清空所有数据"):
            st.session_state.participants = []
            st.session_state.votes = {}
            st.session_state.current_user = None
            st.rerun()

# 管理员模式
if st.session_state.get('admin_mode'):
    st.header("??? 管理员视图")
    
    # 添加参与者
    st.subheader("添加参与者")
    col1, col2 = st.columns([3, 1])
    with col1:
        new_participant = st.text_input("参与者姓名", key="admin_add")
    with col2:
        if st.button("添加", key="admin_add_btn") and new_participant:
            if new_participant not in st.session_state.participants:
                st.session_state.participants.append(new_participant)
                st.success(f"已添加: {new_participant}")
                st.rerun()
    
    if st.session_state.participants:
        st.subheader("所有参与者")
        for i, p in enumerate(st.session_state.participants):
            col1, col2 = st.columns([3, 1])
            with col1:
                st.write(f"{i+1}. {p}")
            with col2:
                if st.button("删除", key=f"del_{i}"):
                    st.session_state.participants.remove(p)
                    if p in st.session_state.votes:
                        del st.session_state.votes[p]
                    st.rerun()
        
        st.subheader("投票进度")
        voted_count = len(st.session_state.votes)
        total_count = len(st.session_state.participants)
        st.progress(voted_count / total_count if total_count > 0 else 0)
        st.write(f"已完成: {voted_count}/{total_count} 人")
        
        if st.session_state.votes:
            st.subheader("投票数据")
            votes_data = []
            for voter, votes_dict in st.session_state.votes.items():
                for target, score in votes_dict.items():
                    votes_data.append({"投票者": voter, "被投者": target, "得分": score})
            st.dataframe(pd.DataFrame(votes_data))
            
            st.subheader("互选匹配结果")
            mutual_affinity = calculate_mutual_affinity()
            if mutual_affinity:
                mutual_data = []
                for user, matches in mutual_affinity.items():
                    for match_user, score in matches.items():
                        mutual_data.append({"用户": user, "匹配对象": match_user, "好感度": score})
                mutual_df = pd.DataFrame(mutual_data)
                st.dataframe(mutual_df.sort_values("好感度", ascending=False))

# 用户模式
else:
    # 用户登录
    if not st.session_state.current_user:
        st.header("请选择您的身份")
        
        if st.session_state.participants:
            selected_user = st.selectbox("选择您的姓名", [""] + st.session_state.participants)
            if selected_user and st.button("确认身份"):
                st.session_state.current_user = selected_user
                st.rerun()
        else:
            st.warning("暂无参与者，请联系活动组织者")
    
    # 用户投票界面
    else:
        st.header(f"?? 欢迎，{st.session_state.current_user}！")
        
        has_voted = st.session_state.current_user in st.session_state.votes
        
        if has_voted:
            st.success("? 您已完成投票")
            
            # 显示投票结果
            st.subheader("您的投票结果")
            user_votes = st.session_state.votes[st.session_state.current_user]
            for i, (target, score) in enumerate(user_votes.items()):
                st.write(f"第{i+1}名：{target} (得{score}分)")
            
            if st.button("重新投票"):
                del st.session_state.votes[st.session_state.current_user]
                st.rerun()
            
            # 显示匹配结果
            show_personal_results()
            
        else:
            st.markdown('<div class="vote-section">请为您喜欢的参与者投票（1-5人）</div>', unsafe_allow_html=True)
            
            vote_options = [p for p in st.session_state.participants if p != st.session_state.current_user]
            
            if not vote_options:
                st.warning("暂无其他参与者可投票")
            else:
                st.write("请按喜欢程度排序：")
                
                vote_count = st.slider("选择投票人数", 1, 5, 3)
                
                selected_votes = {}
                rank_emojis = ["1??", "2??", "3??", "4??", "5??"]
                
                for rank in range(vote_count):
                    points = 5 - rank
                    
                    available_options = [p for p in vote_options if p not in selected_votes]
                    if not available_options:
                        st.warning("没有更多可选的参与者")
                        break
                        
                    rank_options = [f"请选择第{rank+1}名"] + available_options
                    selected = st.selectbox(
                        f"{rank_emojis[rank]} 第{rank+1}名（得{points}分）", 
                        rank_options,
                        key=f"vote_{rank}"
                    )
                    
                    if selected != f"请选择第{rank+1}名":
                        selected_votes[selected] = points
                
                if len(selected_votes) == vote_count:
                    if st.button("提交投票"):
                        st.session_state.votes[st.session_state.current_user] = selected_votes
                        st.success("投票成功！")
                        st.balloons()
                        st.rerun()

st.markdown("---")
st.markdown("多人在线实时匹配系统 | 每人用自己的手机投票")